package com.qf.base.util;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author 汤奇
 * @version V1.0
 * @Project BookPro
 * @Package com.qf.base.util
 * @Description: 异步处理工具类
 * @Date 2022/8/6 19:21
 */
public class AsyncBatchCallUtil {
    /**
     * 对外界提供方法
     */
    public static void execute(Runnable task){
        executorService.execute(task);
    }

    /**
     * 线程池服务
     */
    private static ExecutorService executorService;

    static {
        //核心线程数
        int corePoolSize = 4*2;
        //最大线程数
        int maxPoolSize = 4*2;
        //时间
        long keepAliveTime = 10;
        //时间单位
        TimeUnit unit = TimeUnit.SECONDS;
        //队列
        LinkedBlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>();
        //工厂
        UserThreadFactory threadFactory = new UserThreadFactory("QianFeng");
        //拒绝策略
        UserRejectPolicy handler = new UserRejectPolicy();
        //实例化线程池
        executorService = new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
    }

    /**
     * 线程工厂
     */
    static class UserThreadFactory implements ThreadFactory{

        private final String namePrefix;
        private final AtomicInteger nextId = new AtomicInteger(1);

        public UserThreadFactory(String groupName) {
            this.namePrefix = "Form"+UserThreadFactory.class.getName()+"-"+groupName+"-";
        }

        @Override
        public Thread newThread(Runnable r) {
            String name = namePrefix + nextId.getAndIncrement();
            Thread thread = new Thread(null, r, name);
            return thread;
        }
    }

    /**
     * 拒绝策略
     */
    static class UserRejectPolicy implements RejectedExecutionHandler{

        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            System.out.println(AsyncBatchCallUtil.class.getName()+"队列满了");
        }

    }
}
